package me.firstapp.weixin.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.api.OauthApi;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import com.foxinmy.weixin4j.mp.model.User;

import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.weixin.utils.WchatConfig;

@Controller
public class WeiXinCallBackController {

	private static final Logger logger = LoggerFactory.getLogger(WeiXinCallBackController.class);

	private static OauthApi oauthApi = new OauthApi(WchatConfig.getInstance().getWeixinProxy().getWeixinAccount());

	@Value("#{configProperties['weixin.system.openid']}")
	private String systemOpenId;

	@Value("#{configProperties['weixin.system.cardno']}")
	private String systemCardNo;

	@Autowired
	private MemberService memberService;

	@RequestMapping("/redirect.do")
	public ModelAndView redirect(String code, String state, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		if (StrUtils.isNULL(state)) {
			logger.info("[回调地址不存在] code ： " + code + "; state : " + state);
			System.out.println("[回调地址不存在] code ： " + code + "; state : " + state);
		}
		OauthToken oauthToken = null;
		logger.info("[认证回调] code ： " + code + "; state : " + state);
		try {
			oauthToken = oauthApi.getAuthorizationToken(code);
			User user = WchatConfig.getInstance().getWeixinProxy().getUser(oauthToken.getOpenId());
			if (null == user) {
				logger.info("无法获取微信中更多的个人信息,需要重新关注！");
			} else {
				Member member = memberService.findMemberByOpenId(oauthToken.getOpenId());
				if (null == member) {
					memberService.executeAddMember(oauthToken.getOpenId(), systemOpenId, systemCardNo,
							user.getNickName(), user.getHeadimgurl(), null);
				} else {
					memberService.executeUpdateMember(oauthToken.getOpenId(), user.getNickName(), user.getHeadimgurl());
				}
			}
			request.getSession().setAttribute("openId", oauthToken.getOpenId());
		} catch (WeixinException e) {
			e.printStackTrace();
			logger.info("[获取openId异常]" + e);
		}
		// 跳转
		if (null != oauthToken) {
			return new ModelAndView("redirect:" + state, modelMap);
		} else {
			logger.info("[微信用户认证失败]");
			System.out.println("[微信用户认证失败]");
		}
		return new ModelAndView("common/error");
	}
}
